package cn.zane.chatgpt.data.domain.weixin.service.message;

import cn.zane.chatgpt.data.domain.auth.model.entity.MessageTextEntity;
import cn.zane.chatgpt.data.domain.auth.model.entity.UserBehaviorMessageEntity;
import cn.zane.chatgpt.data.domain.auth.model.valobj.MsgTypeVO;
import cn.zane.chatgpt.data.domain.weixin.service.IWeiXinBehaviorService;
import cn.zane.chatgpt.data.types.exception.BaseException;
import cn.zane.chatgpt.data.types.exception.ResultCode;
import cn.zane.chatgpt.data.types.util.sdk.XmlUtil;
import com.google.common.cache.Cache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * @author: zane
 * @date: 2025-09-20
 * @description: 微信行为服务
 */
@Slf4j
@Service
public class WeiXinBehaviorService implements IWeiXinBehaviorService {

    @Value("${wx.config.originalId}")
    private String originalId;

    @Resource
    private Cache<String, String> codeCache;

    /**
     * 微信接受的消息分为两种：消息text和事件event
     *
     * @param userBehaviorMessageEntity 用户行为
     */
    @Override
    public String acceptUserBehavior(UserBehaviorMessageEntity userBehaviorMessageEntity) {
        // EVENT 事件事件，暂且忽略处理
        if (MsgTypeVO.EVENT.equals(userBehaviorMessageEntity.getMsgType())) {
            return "";
        }

        if (MsgTypeVO.TEXT.equals(userBehaviorMessageEntity.getMsgType())) {
            // 缓存验证码
            String isExistCode = codeCache.getIfPresent(userBehaviorMessageEntity.getOpenId());

            // 判断验证码 - 不考虑验证码重复问题
            if (StringUtils.isBlank(isExistCode)) {
                // 创建验证码
                String code = RandomStringUtils.randomNumeric(4);
                codeCache.put(code, userBehaviorMessageEntity.getOpenId());
                codeCache.put(userBehaviorMessageEntity.getOpenId(), code);
                isExistCode = code;
            }

            // 反馈信息[文本]
            MessageTextEntity res = new MessageTextEntity();
            res.setToUserName(userBehaviorMessageEntity.getOpenId());
            res.setFromUserName(originalId);
            res.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000L));
            res.setMsgType(MsgTypeVO.TEXT.getType());
            res.setContent(String.format("您的验证码为：%s 有效期%d分钟！", isExistCode, 3));
            return XmlUtil.beanToXml(res);
        }
        throw new BaseException(ResultCode.FAIL, userBehaviorMessageEntity.getMsgType() + " 未被处理的行为类型 Error！");
    }
}
